//
//  YYCache+SLAdd.m
//  AFNetworking
//
//  Created by 陈镇 on 9/1/20.
//

#import "YYCache+SLAdd.h"

@implementation YYCache (SLAdd)

- (void)sl_setObject:(nullable id<NSCoding>)object inSetForKey:(nonnull NSString *)key {
    if (object == nil) {
        return;
    }
    NSSet *originalSet = (NSSet *)[self objectForKey:key];
    if (originalSet) {
        NSMutableSet *set = [NSMutableSet setWithSet:originalSet];
        [set addObject:object];
        [self setObject:set forKey:key];
    }else {
        [self setObject:[NSSet setWithObject:object] forKey:key];
    }
}

- (void)sl_removeObject:(nullable id<NSCoding>)object inSetForKey:(nonnull NSString *)key {
    if (object == nil) {
        return;
    }
    NSSet *originalSet = (NSSet *)[self objectForKey:key];
    if (originalSet) {
        NSMutableSet *set = [NSMutableSet setWithSet:originalSet];
        [set removeObject:object];
        [self setObject:set forKey:key];
    }
}

- (BOOL)sl_containsObject:(nullable id<NSCoding>)object inSetForKey:(nonnull NSString *)key {
    if (object == nil) {
        return NO;
    }
    NSSet *set = (NSSet *)[self objectForKey:key];
    return [set containsObject:object];
}

- (void)sl_indexObject:(nullable id<NSCoding>)object index:(NSInteger)index inArrayForKey:(nonnull NSString *)key{
    if (object == nil) {
        return;
    }
    NSArray *originalArray = (NSArray *)[self objectForKey:key];
    if (originalArray) {
        NSMutableArray *array = [NSMutableArray arrayWithArray:originalArray];
        [array insertObject:object atIndex:index];
        [self setObject:array forKey:key];
    }else {
        [self setObject:[NSArray arrayWithObject:object] forKey:key];
    }
}
- (void)sl_setObject:(nullable id<NSCoding>)object inArrayForKey:(nonnull NSString *)key{
    if (object == nil) {
        return;
    }
    NSArray *originalArray = (NSArray *)[self objectForKey:key];
    if (originalArray) {
        NSMutableArray *array = [NSMutableArray arrayWithArray:originalArray];
        [array addObject:object];
        [self setObject:array forKey:key];
    }else {
        [self setObject:[NSArray arrayWithObject:object] forKey:key];
    }
}
- (void)sl_removeObject:(nullable id<NSCoding>)object inArrayForKey:(nonnull NSString *)key{
    if (object == nil) {
        return;
    }
    NSArray *originalArray = (NSArray *)[self objectForKey:key];
    if (originalArray) {
        NSMutableArray *array = [NSMutableArray arrayWithArray:originalArray];
        [array removeObject:object];
        [self setObject:array forKey:key];
    }
}
- (BOOL)sl_containsObject:(nullable id<NSCoding>)object inArrayForKey:(nonnull NSString *)key{
    if (object == nil) {
        return NO;
    }
    NSArray *array = (NSArray *)[self objectForKey:key];
    return [array containsObject:object];
}
@end
